package com.gh.shop.product.service.impl;

import org.springframework.stereotype.Service;

import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.gh.common.utils.PageUtils;
import com.gh.common.utils.Query;

import com.gh.shop.product.dao.CategoryDao;
import com.gh.shop.product.entity.CategoryEntity;
import com.gh.shop.product.service.CategoryService;


@Service("categoryService")
public class CategoryServiceImpl extends ServiceImpl<CategoryDao, CategoryEntity> implements CategoryService {

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<CategoryEntity> page = this.page(
                new Query<CategoryEntity>().getPage(params),
                new QueryWrapper<CategoryEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public List<CategoryEntity> listWithTree() {
        List<CategoryEntity> categories = baseMapper.selectList(null);

        //得到一级分类
        List<CategoryEntity> categories1 = categories.stream()
                .filter(categoryEntity -> categoryEntity.getCatLevel() == 1)
                .peek(category -> category.setChildren(getChildren(category, categories)))
                .sorted(Comparator.comparingInt(category -> (category.getSort() == null ? 0 : category.getSort())))
                .collect(Collectors.toList());
        return categories1;
    }

    @Override
    public void removeCategoriesByIds(List<Long> asList) {
        //TODO 检查当前删除的菜单是否被引用
        baseMapper.deleteBatchIds(asList);
    }

    /**
     * 递归查找子分类
     * @param root 父类
     * @param all 所有类
     * @return 子类
     */
    private List<CategoryEntity> getChildren(CategoryEntity root, List<CategoryEntity> all) {
        List<CategoryEntity> children = all.stream()
                .filter(category -> category.getParentCid().equals(root.getCatId()))
                .peek(category -> category.setChildren(getChildren(category, all)))
                .sorted((category1, category2) -> (category1.getSort() == null? 0:category1.getSort()) - (category2.getSort() == null ? 0:category2.getSort()))
                .collect(Collectors.toList());
        return children;

    }

}